package org.jeecg.modules.oa.controller.appController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.controller.CommonController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.modules.oa.entity.OaComment;
import org.jeecg.modules.oa.entity.OaJournal;
import org.jeecg.modules.oa.entity.OaReportWeek;
import org.jeecg.modules.oa.entity.app.CommentRequestEntity;
import org.jeecg.modules.oa.entity.app.JournalRequestEntity;
import org.jeecg.modules.oa.service.IOaCommentService;
import org.jeecg.modules.oa.service.IOaJournalService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/b/app/oaJournal")
public class AppJournalController extends CommonController {
    @Value("${web.imageFileUrl}")
    private String imageFileUrl;

    @Autowired
    private ISysUserService userService;
    @Autowired
    private IOaJournalService journalService;
    @Autowired
    private IOaCommentService commentService;


    /**
     * 根据日期和类型获取当月的日志或周报
     * @param date 日期 2019-01
     * @param type 0 日志和周报 1日志 2周报
     * @return
     */
    @PostMapping(value = "oneMonthJournalOrWeek")
    @ResponseBody
    public Result<?> oneMonthJournalOrWeek(@RequestParam(name = "date") String date, @RequestParam(name = "type") String type, @RequestParam(name = "userId") String userId){
        LoginUser user = SsoUtil.getLoginUser();
        if(user == null || StringUtils.isBlank(user.getId())){
            return Result.error(99,"登录失效");
        }
        if(date.length() != 7 || date.indexOf("-") != 4){
            return Result.error("请填写正确的日期格式，如：2019-01");
        }
        List<OaJournal> journalList = new ArrayList<>();
        List<OaReportWeek> reportWeekList = new ArrayList<>();
        if("0".equals(type) || "1".equals(type)){
            journalList = journalService.appFindJournalList(date,userId);
        }

        return processToResult(date,journalList,reportWeekList,type);
    }

    private Result<?> processToResult(String date,List<OaJournal> journalList,List<OaReportWeek> reportWeekList,String type){
        boolean haveJournal=false,haveWeek=false;
        JSONArray journalArray = new JSONArray(),weekArray = new JSONArray();
        JSONObject resultJson = new JSONObject();
        resultJson.put("date",DateUtils.formatDateTime());
        Map<String,OaJournal> journalMap = new HashMap<>();
        if(journalList != null && journalList.size() > 0 ){
            journalMap = journalList.stream().collect(Collectors.toMap(OaJournal::getCreateTimeStr,OaJournal -> OaJournal));
        }
        if("0".equals(type) || "1".equals(type)){
            haveJournal = true;
        }
        if("0".equals(type) || "2".equals(type)){
            haveWeek = true;
        }
        Date now = new Date();
        //获取当日日报信息
        if(haveJournal){
            OaJournal journalNow = journalMap.get(DateUtils.date_sdf.format(now));
            if(journalNow == null){
                resultJson.put("isHaveJournal",false);
                resultJson.put("contentJournal","暂无数据");
                resultJson.put("idJournal",null);
                resultJson.put("count",0);
            }else{
                resultJson.put("isHaveJournal",true);
                resultJson.put("contentJournal",journalNow.getName());
                resultJson.put("idJournal",journalNow.getId());
                resultJson.put("count",journalNow.getCommentCount());
            }
        }
        //获取本周周报信息
        if(haveWeek){
            boolean isFindNow = false;
            for (OaReportWeek reportWeek : reportWeekList){
                if(now.compareTo(reportWeek.getWorkDateFrom()) > 0 && now.compareTo(reportWeek.getWorkDateTo()) < 0){
                    isFindNow = true;
                    resultJson.put("isHaveWeek",true);
                    resultJson.put("contentWeek",reportWeek.getWorkContent());
                    resultJson.put("idWeek",reportWeek.getId());
                    resultJson.put("count",reportWeek.getCommentCount());
                    break;
                }
            }
            if(!isFindNow){
                resultJson.put("isHaveWeek",false);
                resultJson.put("contentWeek","暂无数据");
                resultJson.put("idWeek",null);
                resultJson.put("count",0);
            }
        }
        String dateStr;Date dateTime;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        int maxDate = calendar.getActualMaximum(Calendar.DATE);
        for (int i = 1 ;i <= maxDate;i++){
            dateStr = date + (i < 10 ?"-0"+i:"-"+i);
            try {
                dateTime = DateUtils.datetimeFormat.parse(dateStr + " 12:00:00");
            } catch (ParseException e) {
                e.printStackTrace();
                return Result.error("日期转换异常");
            }
            Calendar cal = Calendar.getInstance();
            cal.setTime(dateTime);
            int week_day = cal.get(Calendar.DAY_OF_WEEK) - 2;
            if(week_day == -1){
                week_day = 6;
            }
            if(haveJournal){
                OaJournal journal = journalMap.get(dateStr);
                JSONObject json = new JSONObject();
                json.put("date",dateStr);
                json.put("week_day",week_day);
                if(journal == null){
                    json.put("isHave",false);
                    json.put("content","暂无数据");
                    json.put("id",null);
                    json.put("count",0);
                }else{
                    json.put("isHave",true);
                    json.put("content",journal.getName());
                    json.put("id",journal.getId());
                    json.put("count",journal.getCommentCount());
                }
                journalArray.add(json);
            }
            if(haveWeek){
                JSONObject json = new JSONObject();
                json.put("date",dateStr);
                json.put("week_day",week_day);
                boolean isFind = false;
                for (OaReportWeek reportWeek : reportWeekList){
                    if(dateTime.compareTo(reportWeek.getWorkDateFrom()) > 0 && dateTime.compareTo(reportWeek.getWorkDateTo()) < 0){
                        isFind = true;
                        json.put("isHave",true);
                        json.put("content",reportWeek.getWorkContent());
                        json.put("id",reportWeek.getId());
                        json.put("count",reportWeek.getCommentCount());
                        break;
                    }
                }
                if(!isFind){
                    json.put("isHave",false);
                    json.put("content","暂无数据");
                    json.put("id",null);
                    json.put("count",0);
                }
                weekArray.add(json);
            }
        }
        resultJson.put("journalList",journalArray);
        resultJson.put("weekList",weekArray);
        return Result.ok(resultJson);
    }

    /**
     * 根据id获取日志
     *
     * @return
     */
    @PostMapping(value = "getJournalById")
    @ResponseBody
    public Result<?> getJournalById(@RequestParam(name = "id") String id,@RequestParam(name = "userId") String userId) {
        LoginUser user = SsoUtil.getLoginUser();
        if(user == null || StringUtils.isBlank(user.getId())){
            return Result.error(99,"登录失效");
        }
        OaJournal oaJournal = journalService.getById(id);
        if(oaJournal == null){
            return Result.error("日志未找到！");
        }
        JournalRequestEntity journalRequestEntity = new JournalRequestEntity();
        BeanUtils.copyProperties(oaJournal,journalRequestEntity);
        journalRequestEntity.setComments(commentService.findAllMsgById(userId,id));
        return Result.ok(journalRequestEntity);
    }

    /**
     * 新版本日志保存方法
     *
     * @param journalRequestEntity 实体对象
     * @return
     */
    @PostMapping(value = "save")
    @ResponseBody
    public Result save(JournalRequestEntity journalRequestEntity) {
        LoginUser user = SsoUtil.getLoginUser();
        if(user == null || StringUtils.isBlank(user.getId())){
            return Result.error(99,"登录失效");
        }
        OaJournal journal = journalService.getByCreateByAndToday(journalRequestEntity.getUserId());
        if(journal != null){//一天只能新增一次日志
            return Result.error("今日日志已经存在，不允许重复提交");
        }
        journal = new OaJournal();
        journal.setCreateTime(new Date());
        journal.setCreateBy(journalRequestEntity.getUserId());
        journal.setInputTime(new Date());
        journal.setName(journalRequestEntity.getName());
        journal.setInLongitude(journalRequestEntity.getInLongitude());
        journal.setInLatitude(journalRequestEntity.getInLatitude());
        journal.setImageUrl(journalRequestEntity.getImageUrl());
        journal.setInPosition(journalRequestEntity.getInPosition());
        journal.setUnfinishedWork(journalRequestEntity.getUnfinishedWork());
        journal.setNeedhelpWork(journalRequestEntity.getNeedhelpWork());
        journalService.save(journal);
        return Result.ok("保存成功");
    }

    /**
     * 新版本日志编辑方法
     *
     * @param journalRequestEntity 实体对象
     * @return
     */
    @PostMapping(value = "edit")
    @ResponseBody
    public Result edit(JournalRequestEntity journalRequestEntity) {
        LoginUser user = SsoUtil.getLoginUser();
        if(user == null || StringUtils.isBlank(user.getId())){
            return Result.error(99,"登录失效");
        }
        OaJournal journal = journalService.getById(journalRequestEntity.getId());
        if(journal == null){
            return Result.error("日志未找到，编辑失败");
        }
        journal.setUpdateTime(new Date());
        journal.setUpdateBy(journalRequestEntity.getUserId());
        journal.setName(journalRequestEntity.getName());
        journal.setImageUrl(journalRequestEntity.getImageUrl());
        journal.setUnfinishedWork(journalRequestEntity.getUnfinishedWork());
        journal.setNeedhelpWork(journalRequestEntity.getNeedhelpWork());
        journalService.updateById(journal);
        return Result.ok("保存成功");
    }


    @PostMapping(value="saveComment")
    @ResponseBody
    public Result saveComment(CommentRequestEntity commentRequestEntity){
        LoginUser loginUser = SsoUtil.getLoginUser();
        if(loginUser == null || StringUtils.isBlank(loginUser.getId())){
            return Result.error(99,"登录失效");
        }
        SysUser user = userService.getById(commentRequestEntity.getUserId());
        OaComment commentMsg = new OaComment();
        commentMsg.setContent(commentRequestEntity.getContent());   //评论的内容
        commentMsg.setTopicId(commentRequestEntity.getTopicId());  //被评论的日志Id
        commentMsg.setTopicType(commentRequestEntity.getTopicType()); //日志编号
        commentMsg.setParentId(commentRequestEntity.getParentId());//父类评论的ID
        commentMsg.setParentName(commentRequestEntity.getReplyName());
        commentMsg.setReplyId(commentRequestEntity.getReplyId());
        commentMsg.setReplyCommentId(commentRequestEntity.getReplyCommentId());
        commentMsg.setCreateCompany(user.getCompanyId());
        commentMsg.setCreateDepatr(user.getDepartId());
        commentMsg.setCreateBy(user.getId());
        commentMsg.setActualBy(user.getId());
        commentService.save(commentMsg);
        return Result.ok(commentService.findAllMsgById(commentRequestEntity.getUserId(),commentRequestEntity.getTopicId()));

    }

}
